<template>
  <div class="production_container">
    <el-card>
      <div class="user-container-header">
        <div class="user-container-header-left">
          <el-button type="primary" :icon="Plus" @click="handleAdd">添加</el-button>
          <el-button type="danger" :icon="Delete" @click="handleAllDelte">批量删除</el-button>
        </div>
        <div class="user-container-header-right">
          <el-input v-model="search" placeholder="请输入用户名" type="search" />
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
        </div>
      </div>
      <el-dialog
        v-model="isDialog"
        :title="dioDate.id ? '修改' : '添加'"
        width="40%"
        class="shop-dialog"
        :close-on-click-modal="false"
        destroy-on-close
      >
        <el-form
          :model="dioDate"
          :rules="dioRule"
          ref="shopFormRef"
          label-width="100px"
          class="shop-form"
        >
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="dioDate.name" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="商品图片" prop="img">
            <el-upload
              class="shop-upload"
              :drag="true"
              action="/api/upload/image"
              :limit="1"
              :http-request="customUpload"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :before-upload="beforeUpload"
              :before-remove="beforeRemove"
              :on-exceed="handleExceed"
            >
              <div class="upload-area">
                <div class="upload-placeholder">
                  <el-icon class="upload-icon"><UploadFilled /></el-icon>
                  <div class="upload-text">点击或拖拽图片上传</div>
                </div>

                <div class="el-upload__tip">jpg/png/webp文件大小不能超过5M</div>
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品售价" prop="sales">
            <el-input v-model="dioDate.sales" style="width: 100%" />
          </el-form-item>

          <el-form-item label="商品状态" prop="state">
            <el-select v-model="dioDate.state" placeholder="请选择状态" style="width: 100%">
              <el-option v-for="item in dioDate.state" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="商品类型" prop="shopType">
            <el-select v-model="dioDate.shopType" placeholder="请选择状态" style="width: 100%">
              <el-option v-for="item in dioDate.shopType" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="商品库存" prop="inv">
            <el-input v-model="dioDate.inv" style="width: 100%" />
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="saveInfo" v-if="dioDate.id">确 定</el-button>
            <el-button type="primary" @click="addInfo" v-else>确 定</el-button>
          </div>
        </template>
      </el-dialog>
      <Table
        :tableData="shopTableDate"
        :columns="columns"
        @selectionChange="handleSelection"
        @edit="handleEdit"
        @delete="handleDelete"
      ></Table>
      <div class="pagination-box">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <Footer></Footer>
  </div>
</template>

<script setup lang="ts">
import Footer from "@/components/reuse/footer.vue";
import Table from "@/components/reuse/shopTable.vue";
import https from "@/utils/https";
import { ref, onMounted, reactive } from "vue";
import { Plus, Delete, Search, UploadFilled } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";

// 商品列表
const shopTableDate = reactive([{}]);
// columns
const columns = ref([
  {
    label: "商品ID",
    prop: "shopId",
  },
  {
    label: "商品名称",
    prop: "name",
  },
  { label: "商品售价", prop: "price" },
  { label: "销量", prop: "sales" },
  { label: "库存", prop: "inv" },
  { label: "时间", prop: "time" },
]);
const background = ref(true);
// 当前页
const currentPage = ref<number | string>(2);
// 每页条数
const pageSize = ref<number | string>(10);
// 总条数
const total = ref<number>(0);
// 搜索
const search = ref("");
const isDialog = ref(false);
const allShopChange = ref<any[]>([]);
// dio对象
const dioDate = reactive({
  id: "",
  name: "",
  img: ["", "", "", ""],
  shopType: ["家用电器", "食品饮料", "其他"],
  state: ["待上架", "已上架", "已下架"],
  sales: "",
  inv: "",
});
// 表单验证
const dioRule = reactive({
  name: [{ required: true, message: "请输入商品名称" }],
  sales: [{ required: true, message: "请输入商品售价" }],
  inv: [{ required: true, message: "请输入库存" }],
});
// 全选
const handleSelection = (val: any) => {
  allShopChange.value = val;
};
const getShopList = async () => {
  const res = await https.get("/\/api\/shop.*/", {
    params: {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
    },
  });
  console.log(res);
  Object.assign(shopTableDate, res.data.list);
  total.value = res.data.total;
  currentPage.value = res.data.currentPage;
  pageSize.value = res.data.pageSize;
};
// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  getShopList();
};
// 处理当前页变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  getShopList();
};
//保存数据
const saveInfo = async () => {
  try {
    const res = await https.put("/shop/put", {
      id: dioDate.id,
      data: {
        name: dioDate.name,
        img: dioDate.img,
        sales: dioDate.sales,
        shopType: dioDate.shopType,
        inv: dioDate.inv,
        state: dioDate.state,
      },
    });

    if (res.data.code === 200) {
      ElMessage.success("修改成功");
      isDialog.value = false;
      getShopList(); // 刷新列表
    } else {
      ElMessage.error(res.data.message || "修改失败");
    }
  } catch (error) {
    console.error("修改错误:", error);
    ElMessage.error("修改失败");
  }
};
// 添加数据
const handleAdd = async () => {
  isDialog.value = true;
  Object.assign(dioDate, {
    id: "",
    name: "",
    img: "",
    sales: "",
    inv: "",
  });
};
const addInfo = async () => {
  const res = await https.post("/shop/add", dioDate);
  if ((res.code = 200)) {
    ElMessage({
      type: "success",
      message: "添加成功",
    });
    isDialog.value = false;
    Object.assign(dioDate, {
      name: "",
      img: [],
      sales: "",
      inv: "",
      state: "",
    });
  } else {
    ElMessage.error("添加失败");
  }
};
// 添加自定义上传方法
const customUpload = (options: any) => {
  const { file, onSuccess } = options;
  // 模拟上传
  setTimeout(() => {
    onSuccess({
      code: 200,
      message: "success",
      data: ["https://img2.baidu.com/it/u=4107181646,143803062&fm=253&fmt=auto?w=1280&h=800"],
    });
  }, 300);
};
const beforeUpload = (upload: any) => {
  console.log(upload);
  if (upload.type === "image/jpeg" || upload.type === "image/png" || upload.type === "image/webp") {
    // ElMessage({
    //   type: "success",
    //   message: "文件上传格式正确",
    // });
    ElMessage.success("文件上传格式正确");
    const isLt5M = upload.size / 1024 / 1024 < 5; // 将文件大小限制为小于5MB
    if (!isLt5M) {
      ElMessage.error("文件大小不能超过5M");
    } else {
      ElMessage.success("文件上传大小检验正确");
    }
  } else {
    ElMessage.error("文件上传格式必须是图片类型");
  }
};
const handleSuccess = (response: any, file: any) => {
  if (response.code === 200) {
    dioDate.img = response.data[0]; // 保存返回的图片URL
    ElMessage.success("上传成功");
  } else {
    ElMessage.error("上传失败");
  }
};
// 全选删除
const handleAllDelte = async () => {
  if (!allShopChange.value || allShopChange.value.length === 0) {
    ElMessage.warning("请先选择要删除的数据");
    return;
  }

  ElMessageBox.confirm("您确定要删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      const res = await https.delete("/shop/AllDelete", {
        data: {
          ids: allShopChange.value,
        },
      });

      if (res.code === 200) {
        ElMessage.success("删除成功");
        // 从本地数据中移除被删除的项
        allShopChange.value.forEach((item: any) => {
          const index = shopTableDate.findIndex((shop: any) => shop.id === item.id);
          if (index > -1) {
            shopTableDate.splice(index, 1);
          }
        });
        // 清空选中数据
        allShopChange.value = [];
        // 重新获取列表
        // getShopList();
      } else {
        ElMessage.error(res.data.message || "删除失败");
      }
    } catch (error) {
      console.error("删除错误:", error);
      ElMessage.error("删除失败");
    }
  });
};
//修改数据
const handleEdit = (row: any) => {
  isDialog.value = true;
  console.log(row);
  Object.assign(dioDate, {
    id: row.id,
    name: row.name,
    image: row.img,
    sales: row.sales,
    inv: row.inv,
    price: row.price,
  });
};
// 删除数据
const handleDelete = async (row: any) => {
  const res = await https.delete("/shop/delete", {
    data: {
      ids: row.id,
    },
  });
  if (res.data.code === 200) {
    ElMessage.success("删除成功");
    getShopList();
  } else {
    ElMessage.error("删除失败");
  }
};
// 查询
const handleSearch = async () => {
  if (!search.value.trim()) {
    ElMessage.warning("请输入搜索关键词");
    return;
  }

  try {
    const res = await https.get("/shop/search", {
      params: {
        keyword: search.value,
        currentPage: currentPage.value,
        pageSize: pageSize.value,
      },
    });
    if (res.code === 200) {
      Object.assign(shopTableDate, res.data.list);
      total.value = res.data.total;
      currentPage.value = res.data.currentPage;
      pageSize.value = res.data.pageSize;
      search.value = "";
    } else {
      ElMessage.error(res.data.message || "搜索失败");
    }
  } catch (error) {
    console.error("搜索错误:", error);
    ElMessage.error("搜索失败");
  }
};
onMounted(() => {
  getShopList();
});
</script>

<style scoped>
.user-container-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24px;
}

.user-container-header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}
.add-form {
  width: 400px;
}

.user-container-header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}
.pagination-box {
  display: flex;
  justify-content: center;
  margin-top: 15px;
}

.shop-dialog {
  :deep(.el-dialog__body) {
    padding: 20px 30px;
  }
}

.shop-form {
  margin-top: 10px;
  .el-form-item {
    margin-bottom: 20px;
  }
}

.shop-upload {
  width: 100%;

  .upload-area {
    width: 100%;
    height: 200px;
    /* border: 1px dashed var(--el-border-color); */
    border-radius: 8px;
    transition: all 0.3s;

    &:hover {
      border-color: var(--el-color-primary);
    }
  }

  .preview-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 8px;
  }

  .upload-placeholder {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: var(--el-text-color-secondary);

    .upload-icon {
      font-size: 40px;
      margin-bottom: 8px;
    }

    .upload-text {
      font-size: 14px;
    }
  }
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;

  .el-button + .el-button {
    margin-left: 12px;
  }
}

/* 深色模式适配 */
:deep(.el-dialog) {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-light);
  box-shadow: var(--el-box-shadow-light);
}
</style>
